package com.fumin.controller;

import com.alibaba.fastjson.JSONObject;
import com.fumin.Filtter.BussinessException;
import com.fumin.pojo.BusinessResponse;
import org.apache.log4j.Logger;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolationException;

/**
 * Created by Lingo on 2018/4/6.
 */
@ControllerAdvice("com.fumin.controller")
public class ExceptionController {

    private static final Logger LOGGER = Logger.getLogger(ExceptionController.class);

    @ExceptionHandler(Exception.class)
    @ResponseBody
    Object handleException(Exception e){
        LOGGER.error(e.getMessage(), e);
        ExceptionResponse response = new ExceptionResponse("系统忙，请稍后再试");
        return response;
    }

    @ExceptionHandler(BussinessException.class)
    @ResponseBody
    Object handleBusinessException(BussinessException e){
        LOGGER.error(e.getMessage(), e);
        ExceptionResponse response = new ExceptionResponse(e.getMessage());
        return response;
    }

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public String handleValidationException(ConstraintViolationException e) {
        return e.getConstraintViolations().stream()
                .map(message -> message.getInvalidValue() + ":" + message.getMessage() + "<br/>")
                .reduce("", (s0, s1) -> s0 + s1);

    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Object handleValidationException(MethodArgumentNotValidException e) {
        JSONObject result = new JSONObject();
        for (FieldError fieldError:e.getBindingResult().getFieldErrors()) {
            result.put(fieldError.getField(),fieldError.getDefaultMessage());
        }
        return result;
    }









    private class ExceptionResponse{
        private String code="-1";
        private String message;

        public ExceptionResponse(String message) {
            this.message = message;
        }

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }
    }

}
